﻿using MVC4App.Repositories.Core;
using MVC4App.SecurityServiceReference;

namespace MVC4App.Repositories.Implementations
{
    /// <summary>
    /// Authentication Repository class.
    /// Note: this repository class is different from others (i.e. no CRUD operations) 
    /// and therefore does not need to implement IRepository<T/> (like all other repositories).
    /// </summary>
    public class AuthRepository : RepositoryBase, IAuthRepository
    {
        /// <summary>
        /// GetToken must be the first call into web service. 
        /// It establishes a session on the server and retrieves a newly created accesstoken.
        /// </summary>
        /// <returns>Unique access token that is valid for the duration of the session.</returns>
        public string GetToken()
        {
            var request = new TokenRequest {RequestId = RequestHelper.RequestId, ClientTag = RequestHelper.ClientTag};                        
            var response = SecurityServiceClient.GetToken(request);

            Correlate(request, response);

            return response.AccessToken;
        }

        /// <summary>
        /// Login to the system.
        /// </summary>
        /// <param name="username">User name.</param>
        /// <param name="password">Password.</param>
        /// <returns>Success or failure flag.</returns>
        public LoginResponse Login(string username, string password)
        {
            var request = new LoginRequest().Prepare();
            request.UserName = username;
            request.Password = password;

            var response = SecurityServiceClient.Login(request);

            Correlate(request, response);

            return response;
        }

        /// <summary>
        /// Logout from from the system.
        /// </summary>
        /// <returns>Success or failure flag.</returns>
        public bool Logout()
        {
            var request = new LogoutRequest().Prepare();
            var response = SecurityServiceClient.Logout(request);
            Correlate(request, response);
            return response.Acknowledge == AcknowledgeType.Success;
        }
    }
}